#pragma once
#include <iostream>
#include <queue>
#include <pthread.h>

template <class T>
class BlockQueue
{
    bool isfull()
    {
        return _q.size() == _cap;
    }
    bool isempty()
    {
        return _q.empty();
    }

public:
    BlockQueue(int cap = 6)
        : _cap(cap)
    {
        _producer_wait_num = 0;
        _consumer_wait_num = 0;
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond_consumer, nullptr);
        pthread_cond_init(&_cond_producer, nullptr);
    }

    void Enqueue(const T &data)
    {
        pthread_mutex_lock(&_mutex);
        while (isfull())
        {
            _producer_wait_num++;
            pthread_cond_wait(&_cond_producer, &_mutex);
            _producer_wait_num--;
        }
        _q.push(data);
        if (_consumer_wait_num > 0)
            pthread_cond_signal(&_cond_consumer);
        pthread_mutex_unlock(&_mutex);
    }
    void Pop(T *out)
    {
        pthread_mutex_lock(&_mutex);
        while (isempty())
        {
            _consumer_wait_num++;
            pthread_cond_wait(&_cond_consumer, &_mutex);
            _consumer_wait_num--;
        }
        *out = _q.front();
        _q.pop();
        if (_producer_wait_num > 0)
            pthread_cond_signal(&_cond_producer);
        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond_consumer);
        pthread_cond_destroy(&_cond_producer);
    }

private:
    std::queue<T> _q;
    int _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond_producer;
    pthread_cond_t _cond_consumer;

    int _producer_wait_num;
    int _consumer_wait_num;
};
